<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>自定义axios请求函数</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.11.0/qs.js"></script>
  </head>
  <body>
    <button>点击发送 GET 请求</button>
    <button>点击发送 POST 请求</button>
    <button>点击发送 PUT 请求</button>
    <button>点击发送 DELETE 请求</button>



    <script>
        function axios({url,method='GET',params={},data={}}){
            return new Promise((resolve,reject)=>{
                const queryStr = Qs.stringify(params)
                if(queryStr){
                    url += '?' +queryStr
                }
                method = method.toUpperCase()
                const xhr = new XMLHttpRequest()
                xhr.open(method, url)
                xhr.onreadystatechange = ()=>{
                    if(xhr.readyState === 4){
                        const status = xhr.status
                        if(status>=200&&status<=299){
                            const response = {
                                data:JSON.parse(xhr.responseText),
                                status,
                                statusText:xhr.statusText
                            }
                            resolve(response)
                        }else{
                            const error  = new Error('请求出错， status=' + status)
                            reject(error)
                        }
                    }
                }
                if(method === 'GET'){
                    xhr.send()
                }else{
                    xhr.setRequestHeader('Content-Type', 'application/json')
                    xhr.send(JSON.stringify(data))
                }
            })
        }
        /* 封装axios的静态方法 */
        axios.get = function(url,config){
            return axios({
                ...config,url,method:'GET'
            })
        }
        axios.delete = function(url,config){
            return axios({
                ...config,url,method:'DELETE'
            })
        }
        axios.post = function(url,config){
            return axios({
                ...config,url,method:'POST',data
            })
        }
        axios.put = function (url, data, config) {
        return axios({...config, url, method: 'put', data})
      }







    </script>

    <script>
      const buttons = document.querySelectorAll('button')

      // get请求
       buttons[0].onclick = async () => {
        try {
          
          const response = await axios.get(`http://localhost:3000/movie`, {
            params: {
              id: 2,
              name: 'aa'
            }
          })
          console.log(response)
        } catch (error) {
          console.log(error)
          alert(error.message)
        }
      }

      // 添加
      buttons[1].onclick = async () => {
        const response = await axios.post('http://localhost:3000/movie',{
            name:'aa',
            director:'bb'
        })
        console.log(response.data)
      }

      // 更新 
      buttons[2].onclick = async () => {
        const response = await axios.put('http://localhost:3000/movie/6', { // 内部会自动转换为Json, 并指定相应Content-Type请求头
            name: '野外生存记6',
            director: '贝爷15'
          })
        console.log(response.data)
      }

      // 删除
      buttons[3].onclick = async () => {

        const response = await axios.delete('http://localhost:3000/movie/5')
        console.log(response.data)
      }

    </script>
  </body>
</html>
